package com.uvstu.web.controller.common;

import cn.uvtool.utils.QrCodeUtil;
import com.alibaba.fastjson2.JSONObject;
import com.uvstu.common.pay.client.WxPayClient;
import com.uvstu.system.domain.SApplication;
import com.uvstu.system.domain.SOrder;
import com.uvstu.system.domain.SUorder;
import com.uvstu.system.service.*;
import com.uvstu.common.utils.HttpsUtil;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.util.*;

/**
 * 支付开放层 openPayApiController
 *
 * @author zwb
 * @date 2023-02-02
 */
@RestController
@RequestMapping("/open/pay/api")
public class OpenPayApiController {

    @Autowired
    private ISOrderService isOrderService;

    @Autowired
    private ISUorderService isUorderService;

    @Autowired
    private ISApplicationService applicationService;

    @Autowired
    private ISPayConfigService isPayConfigService;

    @Autowired
    private ISysConfigService configService;

    /**
     * 支付宝支付结果通知
     * @param request
     */
    @RequestMapping("aliPayNotify")
    public String aliPayNotify(HttpServletRequest request){
        try{
            Map<String, String> params = new HashMap();
            Map<String, String[]> requestParams = request.getParameterMap();
            Iterator<String> iter = requestParams.keySet().iterator();

            while(iter.hasNext()) {
                String name = (String)iter.next();
                String[] values = (String[])requestParams.get(name);
                String valueStr = "";
                for(int i = 0; i < values.length; ++i) {
                    valueStr = i == values.length - 1 ? valueStr + values[i] : valueStr + values[i] + ",";
                }
                valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
                params.put(name, valueStr);
            }
            if("TRADE_SUCCESS".equals(params.get("trade_status"))){
                String tradeNo = params.get("trade_no");
                String outTradeNo = params.get("out_trade_no");
                //查询该订单
                SOrder sOrder = new SOrder();
                sOrder.setOrderId(outTradeNo);
                sOrder.setTradeNo(tradeNo);
                isOrderService.paySuccess(sOrder);
                sOrder = isOrderService.selectSOrderByTradeNo(sOrder);
                if(sOrder.getGoodName().indexOf("[续费]") != -1){
                    sOrder.setGoodName(sOrder.getGoodName().replace("[续费]",""));
                    //续费处理
                    SOrder oldOrder = new SOrder();
                    oldOrder.setUserId(sOrder.getUserId());
                    oldOrder.setStatus(2);
                    //获取用户可用订单
                    List<SOrder> sOrderList = isOrderService.selectUserOrder(oldOrder);
                    if(sOrderList.size() != 0){
                        //之前订单失效
                        oldOrder = sOrderList.get(0);
                        oldOrder.setStatus(7);
                        isOrderService.updateSOrder(oldOrder);
                        //当前订单生效
                        sOrder.setStatus(2);
                        isOrderService.paySuccess(sOrder);
                    }else{
                        sOrder.setStatus(2);
                        isOrderService.paySuccess(sOrder);
                    }
                }else if(sOrder.getGoodName().indexOf("[升级]") != -1){
                    //升级处理
                    sOrder.setGoodName(sOrder.getGoodName().replace("[升级]",""));
                    //续费处理
                    SOrder oldOrder = new SOrder();
                    oldOrder.setUserId(sOrder.getUserId());
                    oldOrder.setStatus(2);
                    //获取用户可用订单
                    List<SOrder> sOrderList = isOrderService.selectUserOrder(oldOrder);
                    if(sOrderList.size() != 0){
                        //之前订单失效
                        oldOrder = sOrderList.get(0);
                        oldOrder.setStatus(7);
                        isOrderService.updateSOrder(oldOrder);
                        //当前订单生效
                        sOrder.setStatus(2);
                        isOrderService.paySuccess(sOrder);
                    }else{
                        sOrder.setStatus(2);
                        isOrderService.paySuccess(sOrder);
                    }
                }else {
                    sOrder.setStatus(2);
                    isOrderService.paySuccess(sOrder);
                }
                //更新所有的应用的支付通道
                SApplication sApplication = new SApplication();
                sApplication.setPayMethod(sOrder.getPayMethod());
                sApplication.setUserId(sOrder.getUserId());
                applicationService.updateSApplicationPayMethod(sApplication);
            }
            return "success";
        }catch (Exception e){
            e.printStackTrace();
        }
        return "error";
    }

    /**
     * 微信支付结果通知
     * @param req
     */
    @RequestMapping("wxPayNotify")
    public String wxPayNotify(@RequestBody String req){
        try{
            Map<String,String> params = WxPayClient.payResult(req);
            if("SUCCESS".equals(params.get("result_code"))){
                String tradeNo = params.get("transaction_id");
                String outTradeNo = params.get("out_trade_no");
                SOrder sOrder = new SOrder();
                sOrder.setOrderId(outTradeNo);
                sOrder.setTradeNo(tradeNo);
                isOrderService.paySuccess(sOrder);
                sOrder = isOrderService.selectSOrderByTradeNo(sOrder);
                if(sOrder.getGoodName().indexOf("[续费]") != -1){
                    sOrder.setGoodName(sOrder.getGoodName().replace("[续费]",""));
                    //续费处理
                    SOrder oldOrder = new SOrder();
                    oldOrder.setUserId(sOrder.getUserId());
                    oldOrder.setStatus(2);
                    //获取用户可用订单
                    List<SOrder> sOrderList = isOrderService.selectUserOrder(oldOrder);
                    if(sOrderList.size() != 0){
                        //之前订单失效
                        oldOrder = sOrderList.get(0);
                        oldOrder.setStatus(7);
                        isOrderService.updateSOrder(oldOrder);
                        //当前订单生效
                        sOrder.setStatus(2);
                        isOrderService.paySuccess(sOrder);
                    }else{
                        sOrder.setStatus(2);
                        isOrderService.paySuccess(sOrder);
                    }
                }else if(sOrder.getGoodName().indexOf("[升级]") != -1){
                    //升级处理
                    sOrder.setGoodName(sOrder.getGoodName().replace("[升级]",""));
                    //续费处理
                    SOrder oldOrder = new SOrder();
                    oldOrder.setUserId(sOrder.getUserId());
                    oldOrder.setStatus(2);
                    //获取用户可用订单
                    List<SOrder> sOrderList = isOrderService.selectUserOrder(oldOrder);
                    if(sOrderList.size() != 0){
                        //之前订单失效
                        oldOrder = sOrderList.get(0);
                        oldOrder.setStatus(7);
                        isOrderService.updateSOrder(oldOrder);
                        //当前订单生效
                        sOrder.setStatus(2);
                        isOrderService.paySuccess(sOrder);
                    }else{
                        sOrder.setStatus(2);
                        isOrderService.paySuccess(sOrder);
                    }
                }else {
                    sOrder.setStatus(2);
                    isOrderService.paySuccess(sOrder);
                }
                //更新所有的应用的支付通道
                SApplication sApplication = new SApplication();
                sApplication.setPayMethod(sOrder.getPayMethod());
                sApplication.setUserId(sOrder.getUserId());
                applicationService.updateSApplicationPayMethod(sApplication);
                return "<xml>" +
                        "  <return_code><![CDATA[SUCCESS]]></return_code>" +
                        "  <return_msg><![CDATA[OK]]></return_msg>" +
                        "</xml>";
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return "error";
    }

    /**
     * 微信退款结果通知
     * @param req
     */
    @RequestMapping("wxRefundNotify")
    public String wxRefundNotify(@RequestBody String req){
        try{
            Map<String,String> params = WxPayClient.refundResult(req);
            if("SUCCESS".equals(params.get("refund_status"))){
                String tradeNo = params.get("transaction_id");
                String outTradeNo = params.get("out_refund_no");
                SOrder sOrder = new SOrder();
                sOrder.setOrderId(outTradeNo);
                sOrder.setTradeNo(tradeNo);
                sOrder.setStatus(5);
                isOrderService.paySuccess(sOrder);
                sOrder = isOrderService.selectSOrderByTradeNo(sOrder);
                //更新所有的应用的支付通道
                SApplication sApplication = new SApplication();
                sApplication.setStatus(1);
                sApplication.setUserId(sOrder.getUserId());
                applicationService.updateSApplicationStatus(sApplication);
                return "<xml>" +
                        "  <return_code><![CDATA[SUCCESS]]></return_code>" +
                        "  <return_msg><![CDATA[OK]]></return_msg>" +
                        "</xml>";
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return "error";
    }

    /**
     * 用户订单-支付宝支付结果通知
     * @param request
     */
    @RequestMapping("uAliPayNotify")
    public String uAliPayNotify(HttpServletRequest request){
        try{
            Map<String, String> params = new HashMap();
            Map<String, String[]> requestParams = request.getParameterMap();
            Iterator<String> iter = requestParams.keySet().iterator();

            while(iter.hasNext()) {
                String name = (String)iter.next();
                String[] values = (String[])requestParams.get(name);
                String valueStr = "";
                for(int i = 0; i < values.length; ++i) {
                    valueStr = i == values.length - 1 ? valueStr + values[i] : valueStr + values[i] + ",";
                }
                valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
                params.put(name, valueStr);
            }
            System.out.println("支付宝通知入参："+JSONObject.toJSONString(params));
            if("TRADE_SUCCESS".equals(params.get("trade_status"))){
                String tradeNo = params.get("trade_no");
                String outTradeNo = params.get("out_trade_no");
                SUorder sUorder = new SUorder();
                sUorder.setOutTradeNo(outTradeNo);
                sUorder.setTradeNo(tradeNo);
                sUorder.setTransactionTime(new Date());
                sUorder.setStatus(2);
                sUorder.setPayParam(JSONObject.toJSONString(params));
                isUorderService.updateSUorderResult(sUorder);
                try{
                    //发送结果给用户
                    //查询应用
                    sUorder = isUorderService.selectSUorderByOutTradeNo(sUorder);
                    SApplication sApplication = applicationService.selectSApplicationByAppid(sUorder.getAppId());
                    //通知第三方用户支付结果
                    JSONObject data = new JSONObject();
                    data.put("appid",sUorder.getAppId());
                    data.put("outTradeNo",sUorder.getOutTradeNo());
                    data.put("tradeNo",sUorder.getTradeNo());
                    data.put("refundNo",sUorder.getRefundNo());
                    data.put("goodName",sUorder.getGoodName());
                    data.put("payMethod",sUorder.getPayMethod());
                    data.put("price",sUorder.getPrice());
                    data.put("transactionTime",sUorder.getTransactionTime());
                    data.put("status",sUorder.getStatus());
                    data.put("refundTime",sUorder.getRefundTime());
                    data.put("createTime",sUorder.getCreateTime());
                    HttpsUtil.doPost(sApplication.getNotifyUrl(),JSONObject.toJSONString(data));
                }catch (Exception e){
                    System.err.println("支付结果通知失败！");
                }
            }
            return "success";
        }catch (Exception e){
            e.printStackTrace();
        }
        return "error";
    }

    /**
     * 用户订单-微信支付结果通知
     * @param req
     */
    @RequestMapping("uWxPayNotify")
    public String uWxPayNotify(@RequestBody String req){
        try{
            Map<String,String> params = WxPayClient.payResult(req);
            if("SUCCESS".equals(params.get("result_code"))){
                String tradeNo = params.get("transaction_id");
                String outTradeNo = params.get("out_trade_no");
                SUorder sUorder = new SUorder();
                sUorder.setOutTradeNo(outTradeNo);
                sUorder.setTradeNo(tradeNo);
                sUorder.setTransactionTime(new Date());
                sUorder.setStatus(2);
                sUorder.setPayParam(JSONObject.toJSONString(params));
                isUorderService.updateSUorderResult(sUorder);
                try{
                    //发送结果给用户
                    //查询应用
                    sUorder = isUorderService.selectSUorderByOutTradeNo(sUorder);
                    SApplication sApplication = applicationService.selectSApplicationByAppid(sUorder.getAppId());
                    //通知第三方用户支付结果
                    JSONObject data = new JSONObject();
                    data.put("appid",sUorder.getAppId());
                    data.put("outTradeNo",sUorder.getOutTradeNo());
                    data.put("tradeNo",sUorder.getTradeNo());
                    data.put("refundNo",sUorder.getRefundNo());
                    data.put("goodName",sUorder.getGoodName());
                    data.put("payMethod",sUorder.getPayMethod());
                    data.put("price",sUorder.getPrice());
                    data.put("transactionTime",sUorder.getTransactionTime());
                    data.put("status",sUorder.getStatus());
                    data.put("refundTime",sUorder.getRefundTime());
                    data.put("createTime",sUorder.getCreateTime());
                    HttpsUtil.doPost(sApplication.getNotifyUrl(),JSONObject.toJSONString(data));
                }catch (Exception e){
                    System.err.println("支付结果通知失败！");
                }
                return "<xml>" +
                        "  <return_code><![CDATA[SUCCESS]]></return_code>" +
                        "  <return_msg><![CDATA[OK]]></return_msg>" +
                        "</xml>";
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return "error";
    }

    /**
     * 用户订单-微信退款结果通知
     * @param req
     */
    @RequestMapping("uWxRefundNotify")
    public String uWxRefundNotify(@RequestBody String req){
        try{
            Map<String,String> params = WxPayClient.refundResult(req);
            if("SUCCESS".equals(params.get("refund_status"))){
                String tradeNo = params.get("transaction_id");
                String outTradeNo = params.get("out_refund_no");
                SUorder sUorder = new SUorder();
                sUorder.setOutTradeNo(outTradeNo);
                sUorder.setTradeNo(tradeNo);
                sUorder.setRefundTime(new Date());
                sUorder.setStatus(5);
                sUorder.setRefundParam(JSONObject.toJSONString(params));
                isUorderService.updateSUorderResult(sUorder);
                try{
                    //发送结果给用户
                    sUorder = isUorderService.selectSUorderByOutTradeNo(sUorder);
                    SApplication sApplication = applicationService.selectSApplicationByAppid(sUorder.getAppId());
                    //通知第三方用户支付结果
                    JSONObject data = new JSONObject();
                    data.put("appid",sUorder.getAppId());
                    data.put("outTradeNo",sUorder.getOutTradeNo());
                    data.put("tradeNo",sUorder.getTradeNo());
                    data.put("refundNo",sUorder.getRefundNo());
                    data.put("goodName",sUorder.getGoodName());
                    data.put("payMethod",sUorder.getPayMethod());
                    data.put("price",sUorder.getPrice());
                    data.put("transactionTime",sUorder.getTransactionTime());
                    data.put("status",sUorder.getStatus());
                    data.put("refundTime",sUorder.getRefundTime());
                    data.put("createTime",sUorder.getCreateTime());
                    HttpsUtil.doPost(sApplication.getRefundUrl(),JSONObject.toJSONString(data));
                }catch (Exception e){
                    System.err.println("退款结果通知失败！");
                }
                return "<xml>" +
                        "  <return_code><![CDATA[SUCCESS]]></return_code>" +
                        "  <return_msg><![CDATA[OK]]></return_msg>" +
                        "</xml>";
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return "error";
    }

    /**
     * 微信二维码生成
     * @param url
     * @param response
     */
    @RequestMapping("getWxQrcode")
    private void getWxQrcode(@Param("url") String url, HttpServletResponse response){
        try{
            QrCodeUtil.setConfig(200);
            BufferedImage bufferedImage = QrCodeUtil.createImage(url);
            QrCodeUtil.getImage(bufferedImage,response);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}
